package com.atguigu.gmall.realtime.utils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Author: Felix
 * Date: 2022/1/4
 * Desc: 日期转换工具类
 * SimpleDateFormat存在线程安全问题
 * 在JDK1.8之后，推荐使用新的日期类替换
 * SimpleDateFormat ===>DateTimeFormatter
 * Date             ===>LocalDateTime
 * Calendar         ===>Instant
 */
public class DateTimeUtil {

    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //将Date类型日期转换为日期字符串
    public static String toYmdhms(Date date){
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        String dateStr = dtf.format(localDateTime);
        return dateStr;
    }

    //将字符串日期转换为时间毫秒数
    public static Long toTs(String dateStr){
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr, dtf);
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    public static void main(String[] args) {
        System.out.println(ZoneId.systemDefault());
    }
}
